package com.dlc.felear.xiaoensale.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dlc.felear.xiaoensale.R;
import com.dlc.felear.xiaoensale.activity.EditMenuActivity;
import com.dlc.felear.xiaoensale.activity.SelectperatorActivity;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.customView.LoadingDialog;
import com.dlc.felear.xiaoensale.dao.ActionStepItemDao;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.entity.ActionStepItem;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.helper.Session;
import com.itdlc.android.library.listener.TextWatcherAdapter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


public class OperatorStepItemAdapter extends BaseAdapter implements View.OnClickListener {

    private static final String TAG = "OperatorStepItemAdapter";
    // 上下文
    private Context context;
    private AppCompatActivity activity;
    // 数据
    private List<Operator> items;
    private int index = 0;
    private Class aClass = EditMenuActivity.class;
    private boolean enableDelete = true;
    private ActionStepItemDao actionStepItemDao;
    private OperatorDao operatorDao;
    private Session session;
    private LoadingDialog loadingDialog;


    public void setaClass(Class aClass) {
        this.aClass = aClass;
    }

    public void setEnableDelete(boolean flag) {
        enableDelete = flag;
    }

    public OperatorStepItemAdapter(Context context) {
        this.context = context;
        this.activity = (AppCompatActivity) context;
        items = new ArrayList<>();
        session = Session.getSession();
        operatorDao = new OperatorDao(context);
        actionStepItemDao = new ActionStepItemDao(context);
    }

    public List<Operator> getData() {
        return items;
    }


    public void setItems(List<Operator> data) {
        items.clear();
        items.addAll(data);
        notifyDataSetChanged();
    }

    public void updateData(String name, int value, int value2) {
        Log.e(TAG, "name=" + name + " value1=" + value + " value2=" + value2);
        ActionStepItem temp = actionStepItemDao.queryForAllByName(name);
        ;
        Operator operator = items.get(index);
        if (temp != null) {
            operator.setSerial(temp.getSerialNo());
        }
        operator.setName(name);
        operator.setValue(value);
        operator.setValue1(value2);
        items.remove(index);
        items.add(index, operator);
        notifyDataSetChanged();
    }

    public void setItem(Operator operator) {
        if (operator != null) {
            operator.setNum(items.size() + 1);
            items.add(operator);
            notifyDataSetChanged();
        }
    }

    public void clearData() {
        items.clear();
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
//        Log.e(TAG, "getCount()=" + items.size());
        return items.size();
    }

    @Override
    public Operator getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        holder = new ViewHolder();
        convertView = View.inflate(context, R.layout.adapter_operator_step_item, null);
        holder.o_tv_num = convertView.findViewById(R.id.o_tv_num);
        holder.o_tv_select = convertView.findViewById(R.id.o_tv_operator);
        holder.et_time = convertView.findViewById(R.id.o_et_time);
        holder.iv_delete = convertView.findViewById(R.id.o_iv_delete);
        holder.iv_step = convertView.findViewById(R.id.o_iv_step);
        holder.iv_run = convertView.findViewById(R.id.o_iv_run);
        holder.iv_step.setTag(position);
        holder.o_tv_select.setTag(position);
        holder.iv_delete.setTag(position);
        holder.iv_run.setTag(position);
        holder.iv_step.setOnClickListener(this);
        holder.o_tv_select.setOnClickListener(this);
        holder.iv_delete.setOnClickListener(this);
        holder.iv_run.setOnClickListener(this);
        Operator operator = items.get(position);
        holder.et_time.setText(Integer.toString(operator.getDelayTime()));
        String name = TextUtils.isEmpty(operator.getName()) ? "请选择" : operator.getName();
        holder.o_tv_num.setText(operator.getNum() + ":操作:");
        holder.o_tv_select.setText(name);
        if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_JSC)) {
            holder.o_tv_select.setText(name + "_" + operator.getValue());
        }
        if (TextUtils.equals(operator.getName(), Constant.ACTION_NAME_FW)) {
            if (operator.getValue() == 0) {
                holder.o_tv_select.setText(name + "_" + Constant.ACTION_NAME_JSC);
            } else {
                holder.o_tv_select.setText(name + "_" + "锅体");
            }
        }
        setIvSrc(operator.isRun(), holder.iv_run);
        holder.et_time.addTextChangedListener(new TextWatcherAdapter() {
            @Override
            public void afterTextChanged(Editable s) {
                resetOperatorTime(s.toString(), position);
            }
        });
        return convertView;
    }

    private void setIvSrc(boolean flag, ImageView iv) {
        Log.e(TAG, "iv=" + iv);
        if (iv == null) {
            return;
        }
        if (flag) {
            iv.setImageResource(R.drawable.run_icon_1);
        } else {
            iv.setImageResource(R.drawable.run_icon);
        }
    }

    private void resetOperatorTime(String time, int position) {
        if (TextUtils.isEmpty(time)) {
            time = "0";
        }
        Operator operator = items.get(position);
        operator.setDelayTime(Integer.parseInt(time));
        items.remove(position);
        items.add(position, operator);
//        Log.e(TAG,"time="+items.get(position).getDelayTime());
    }


    @Override
    public void onClick(View v) {
        index = (int) v.getTag();
        switch (v.getId()) {
            case R.id.o_iv_run:
//                Log.e(TAG, "ddd");
                stepRun(v);
                break;
            case R.id.o_iv_delete:
//                Log.e(TAG, "ddd");
                deleteData(v);
                break;
            case R.id.o_iv_step:
//                Log.e(TAG, "ddd");
                addData(v);
                break;
            case R.id.o_tv_operator:
//                Log.e(TAG, "ooo");
                if (enableDelete) {
                    showMsg("该模式下不能对操作进行更改");
                    return;
                }
                Intent intent = new Intent(activity, SelectperatorActivity.class);
                activity.startActivityForResult(intent, 1024);
                break;
        }
    }


    private void stepRun(View et) {
        int position = (Integer) et.getTag();
        Operator operator = items.get(position);
        if (!TextUtils.equals("请选择", operator.getName())) {
            if (!operator.isRun()) {
                loadingDialog.show(1000);
                operator.setCurrentTimeStamp(System.currentTimeMillis());
//                byte[] data = OperatorToCmd.getCmdByOperator(session, operator);
//                EventBus.getDefault().post(data, Constant.ACTION_CMD_INFO_DEBUG);
                operator.setRun(true);
                updateOperate(position, operator);
            } else {
                showMsg("提示:该操作已执行过,不能多次执行");
            }

        } else {
            showMsg("请选择有效地操作");
        }
    }

    private void updateOperate(int index, Operator operator) {
        if (index >= 0 && index < items.size()) {

            if (index - 1 >= 0) {
                Operator temp = items.get((index - 1));
                long tempTime = System.currentTimeMillis() - temp.getCurrentTimeStamp();
                temp.setDelayTime(Math.round(tempTime / 1000));
                updateOperateByIndex(index - 1, temp);
            }
            items.remove(index);
            items.add(index, operator);
            notifyDataSetChanged();
        }
    }

    private void updateOperateByIndex(int index, Operator operator) {
        if (index >= 0 && index < items.size()) {
            items.remove(index);
            items.add(index, operator);
            notifyDataSetChanged();
        }
    }

    @Override
    public void notifyDataSetChanged() {
        Collections.sort(items);
        super.notifyDataSetChanged();
    }

    private void addData(View et) {
        if (enableDelete) {
            showMsg("该模式下不能对操作进行删减");
            return;
        }
        int position = (Integer) et.getTag();
        items.add(position + 1, new Operator());
        initNum();
        notifyDataSetChanged();
    }

    private void deleteData(View et) {
        if (enableDelete) {
            showMsg("该模式下不能对操作进行删除");
            return;
        }
        if (items.size() <= 1) {
            showMsg("不能全部删除");
            return;
        }
        int position = (Integer) et.getTag();
        deleteItem(items.get(position));
        items.remove(position);
        initNum();
        notifyDataSetChanged();
    }

    /**
     * 删除已存在的操作步骤
     *
     * @param operator
     */
    private void deleteItem(Operator operator) {
        operatorDao.delete(operator);
    }

    private void initNum() {
        for (int i = 0; i < items.size(); i++) {
            Operator operator = items.get(i);
            operator.setNum(i + 1);
            items.remove(i);
            items.add(i, operator);
        }
    }


    public void setIndex(int position) {
        index = position;
    }

    public void setLoadingDialog(LoadingDialog loadingDialog) {
        this.loadingDialog = loadingDialog;
    }


    static class ViewHolder {
        TextView o_tv_num, o_tv_select;
        EditText et_time;
        ImageView iv_delete, iv_run, iv_step;
    }

    private void showMsg(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

}